package com.taofuxn.admin.api.controller.common;

import com.taofuxn.admin.common.exception.MvcCommonException;
import com.taofuxn.admin.common.exception.ExceptionEnum;
import com.taofuxn.admin.common.model.BaseResults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局controller
 */
@Slf4j
@ControllerAdvice
public class AdviceController {

    /**
     * 异常接收
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public @ResponseBody
    Object exceptionGlob(Exception e) {
        log.error("", e);
        if (e instanceof MvcCommonException) {
            MvcCommonException exception = (MvcCommonException) e;
            ExceptionEnum en = exception.getExceptionEnum();
            if (en != null){
                return BaseResults.fail(en.getCode(), en.getMsg());
            }else{
                return BaseResults.fail(e.getMessage());
            }
        }
        if (StringUtils.isEmpty(e.getMessage())) {
            return BaseResults.fail(ExceptionEnum.COMMON_ERROR.getCode(), ExceptionEnum.COMMON_ERROR.getMsg());
        } else {
            return BaseResults.fail(ExceptionEnum.COMMON_ERROR.getCode(), e.getMessage());
        }
    }

}
